package com.atguigu.gulimall.ssoclient.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 配置域名：client2.com
 */
@Controller
public class HelleController {

    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "hello";
    }

    @GetMapping("/boss")
    public String employees(Model model, HttpSession session,@RequestParam(value = "redisKey", required = false) String redisKey) {
        if (!StringUtils.isEmpty(redisKey)) { // 这个逻辑应该写到过滤器或拦截器里
            RestTemplate restTemplate=new RestTemplate();
            // 拿着token去服务器，在服务端从redis中查出来他的username
            ResponseEntity<String> forEntity =
                    restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?redisKey="+ redisKey, String.class);

            String body = forEntity.getBody();
            // 设置到自己的session中
            session.setAttribute("loginUser", body);
        }

        // session里有就代表登录过 // 获得user
        Object loginUser = session.getAttribute("loginUser");

        if (loginUser == null) { // 又没有loginToken，session里又没有object，去登录页登录
            return "redirect:" + "http://ssoserver.com:8080/login.html"
                    + "?url=http://client2.com:8082/boss";
        } else {// 登录过，执行正常的业务
            List<String> emps = new ArrayList<>();

            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps", emps);
            return "list";
        }
    }

}
